package com.learn.cloud.validator.constraints;

import com.learn.cloud.validator.annotation.StatusValue;
import com.learn.cloud.validator.enums.StatusEnum;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @description: 校验状态，判断是否为 StatusEnum 中的值
 * @author: cong zhi
 * @createDate: 2022/2/6 1:33
 * @updateUser: cong zhi
 * @updateDate: 2022/2/6 1:33
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public class StatusValueValidator implements ConstraintValidator<StatusValue, String> {

    private Boolean required;

    @Override
    public void initialize(StatusValue constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String statusValue, ConstraintValidatorContext context) {
        // 如果是必填的
        if (required && statusValue == null) {
            return false;
        }
        // 如果不是必填，为空则通过
        if (!required && statusValue == null) {
            return true;
        }
        // 校验值是否是枚举中的值
        StatusEnum statusEnum = StatusEnum.codeToEnum(statusValue);
        return statusEnum != null;
    }
}
